import { ConfigService } from './config.service';
import { Component, Output, EventEmitter } from '@angular/core';
import { Http, Response } from '@angular/http';
import swal from 'sweetalert2';
@Component({
  selector: 'upload-primeng',
  template: `
          <div class="panel panel-default">
          <div class="panel-heading">合同附件</div>
          <div class="panel-body">
            <p-fileUpload name="demo[]" [url]="url" (onUpload)="onUpload($event)"
              multiple="multiple" maxFileSize="51200000"> <ng-template
              pTemplate type="content">
                <div class="ui-fileupload-files">
                    <div>
                        <div class="ui-fileupload-row" *ngFor="let file of uploadedFiles; let i = index;">
                            <div>{{file.name}}</div>
                            <div>{{file.size}} bytes</div>
                            <div>已上传</div>
                            <div><button type="button" icon="fa-close" pButton (click)="removeFile(file)"></button></div>
                        </div>
                    </div>
                </div>    
            </ng-template> </p-fileUpload>
          </div>
        </div>
`
})
export class FileUploadPrimeNG {

  public url: string;
  public uploadedFiles: any[] = [];
  @Output() public uploaded: EventEmitter<any> = new EventEmitter();
  @Output() public deleteAllFiles: EventEmitter<any> = new EventEmitter();
  constructor(private config: ConfigService, private http: Http) {
    this.url = this.config.get('batchUpload');
  }
  public onUpload(event) {
    const xhr = event.xhr;
    const resp = JSON.parse(xhr.response);
    if (resp.code === '0000') {
      const info = resp.info;
      let filePath = '';
      for (const file of event.files) {
        info.forEach((p: any) => {
          if (p.fileName === file.name) {
            file.path = p.path;
          }
        });
        this.uploadedFiles.push(file);
        this.uploadedFiles.forEach((f: any) => {
          filePath += ';' + f.path;
        });
      }
      this.uploaded.emit(filePath);
    } else if (resp.code === '4001') {
      swal({
        text: resp.message, type: 'warning'
      }).catch(swal.noop);
    }
  }
  public removeFile(file: any): void {
    swal({
      title: '警告!',
      text: '准备删除已上传文件: ' + file.name,
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定要删除!',
      cancelButtonText: '不，在考虑下!',
      confirmButtonClass: 'btn btn-success',
      cancelButtonClass: 'btn btn-danger',
    }).then((e: any) => {
      const url = this.config.get('delete') + '?filePath=' + file.path;
      this.http.post(url, { filePath: file.path }).toPromise().then((response: Response) => {
        const idx = this.uploadedFiles.indexOf(file);
        this.uploadedFiles.splice(idx, 1);
        if (this.uploadedFiles.length === 0) {
          this.deleteAllFiles.emit(null);
        }
      });
    }, (dismiss: any) => {
      // dismiss can be 'cancel', 'overlay',
      // 'close', and 'timer'
    });
  }
}
